<template>
  <el-dialog
    title="详情"
    v-if="dialogVisible"
    custom-class="workorderPlanDetailDialog"
    append-to-body
    :fullscreen="true"
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
  >
    <div class="dispatch-title">
      <div class="dispatch-title-dot"></div>
      <div class="dispatch-title-text">工单信息</div>
    </div>
    <avue-form class="workInfoForm" v-model="dispatchDialog.workOrderInfo.form" :option="dispatchDialog.workOrderInfo.options"></avue-form>
    <div class="dispatch-title">
      <div class="dispatch-title-dot"></div>
      <div class="dispatch-title-text">产线派工</div>
    </div>
    <div class="dispatch-menu">
      <div class="leftWorkSection">
        产品工段：
        <template v-for="item in dispatchedSectionList"> <span class="finished"></span>{{ item }} </template>
        <template v-for="item in dispatchIngSectionList"> <span class="finishing"></span>{{ item }} </template>
        <template v-for="item in notDispatchSectionList"> <span class="notFinish"></span>{{ item }} </template>
      </div>
      <div class="rightInfo">
        <div class="legendList">
          <div class="legendItem"><span class="finished"></span>已排完</div>
          <div class="legendItem"><span class="finishing"></span>排程中</div>
          <div class="legendItem"><span class="notFinish"></span>未排</div>
        </div>
        <div class="dateDisplay">
          日期展示：
          <el-select size="mini" style="width: 100px" v-model="backDay" placeholder="请选择开始展示日期" @change="handleChangeBackDay">
            <el-option v-for="item in backDayList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <avue-crud class="lineDispatchTable" ref="dispatchCrud" :table-loading="dispatchDialog.plan.loading" :option="dispatchDialog.plan.option" :data="dispatchDialog.plan.data">
      <template slot="sectionAndLineHeader" slot-scope="{ column }"> {{ (column || {}).label }} </template>
      <template slot="sectionAndLine" slot-scope="scope"> {{ scope.row.sectionName }}/{{ scope.row.lineName }} </template>
      <!-- 优先级 -->
      <template slot="priority" slot-scope="{ row }">
        {{ computedPriority(row.priority) }}
        <!-- {{ dispatchDialog.plan.priorityList.find((item) => item.value === row.priority).label }} -->
      </template>
      <template v-for="item in dateColumns" :slot="item.date" slot-scope="{ row, index }">
        <div v-if="item.date.endsWith(':dayPlanQuantity')">{{ row[item.date] }}</div>
        <div v-if="item.date.endsWith(':dayPlanWorkHour')">{{ row[item.date] }}</div>
        <div v-if="item.date.endsWith(':dayRemainingWorkHourOfLine')">{{ row[item.date] }}</div>
      </template>
    </avue-crud>
    <div class="dispatch-title">
      <div class="dispatch-title-dot"></div>
      <div class="dispatch-title-text">操作记录</div>
    </div>
    <avue-crud ref="operateCrud" :table-loading="dispatchDialog.operateRecord.loading" :option="dispatchDialog.operateRecord.option" :data="dispatchDialog.operateRecord.data">
    </avue-crud>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" icon="el-icon-circle-close" @click="closeDialog">关闭</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getPlanInfoList, getProductLineSection, getOperationList, getOperationLog } from '@/api/product/workOrderPlanAps';
import { getDictionary } from '@/api/system/dictbiz.js';
import { mapGetters, mapState } from 'vuex';
import { getDay } from '@/views/product/data/workorderPlan';
const fixedColumns = [
  {
    label: '产线',
    prop: 'sectionAndLine',
    headerslot: true,
    align: 'center',
    fixed: true,
    width: 220
  },
  {
    label: '优先级',
    prop: 'priority',
    headerslot: true,
    fixed: true,
    width: 80,
    align: 'center'
  },
  {
    label: '工段计划数量',
    prop: 'sectionPlanQuantity',
    width: 120,
    fixed: true,
    align: 'center'
  },
  {
    label: '产线已排数量',
    prop: 'linePlanQuantity',
    align: 'center',
    fixed: true,
    width: 80
  },
  {
    label: '工段待排数量',
    prop: 'sectionRemainingQuantity',
    align: 'center',
    fixed: true,
    width: 80
  },
  {
    label: 'UPH(每小时产能)',
    prop: 'uph',
    align: 'center',
    fixed: true,
    width: 105
  }
];
export default {
  name: 'WorkorderPlanDetail',
  components: {},
  data() {
    return {
      workOrderId: '',
      backDay: 5,
      backDayList: [
        {
          label: '5天',
          value: 5
        },
        {
          label: '7天',
          value: 7
        },
        {
          label: '14天',
          value: 14
        },
        {
          label: '30天',
          value: 30
        },
        {
          label: '当月',
          value: 'sameMonth'
        },
        {
          label: '下个月',
          value: 'nextMonth'
        }
      ],
      sectionStatusList: [], // 产线状态列表
      productionLineIds: [],
      productLineSection: [],
      dialogVisible: false,
      productionlineList: [], //产线列表
      dispatchDialog: {
        workOrderInfo: {
          form: {},
          options: {
            submitBtn: false,
            emptyBtn: false,
            labelWidth: 120,
            detail: true,
            column: [
              {
                label: '工单号',
                prop: 'workOrderNo',
                span: 6
              },
              {
                label: '工单类型',
                prop: 'type',
                type: 'select',
                span: 6,
                dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                }
              },
              {
                label: '工单数量',
                prop: 'planQuantity',

                span: 6
              },
              {
                label: '工单状态',
                prop: 'status',
                type: 'select',
                span: 6,
                dataType: 'number',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                },
                dicUrl: '/api/blade-system/dict/dictionary?code=mfg_work_order'
              },
              {
                label: '产品编码',
                prop: 'productPartNo',
                span: 6
              },
              {
                label: '产品型号',
                prop: 'productPartModel',

                span: 6
              },
              {
                label: '产品名称',
                prop: 'productPartName',
                span: 6
              },
              {
                label: '工艺路线状态',
                prop: 'woProcessStatus',
                type: 'select',
                span: 6,
                dicData: [
                  {
                    label: '未设计',
                    value: 1
                  },
                  {
                    label: '待审核',
                    value: 2
                  },
                  {
                    label: '已发布',
                    value: 3
                  }
                ]
              },
              {
                label: '客户编码',
                prop: 'customerCode',
                span: 6
              },
              {
                label: '客户名称',
                prop: 'customerName',
                span: 6
              },
              {
                label: '计划开始时间',
                prop: 'planStartTime',
                type: 'datetime',
                span: 6,
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '计划结束时间',
                prop: 'planEndTime',
                type: 'datetime',
                span: 6,
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '备注',
                prop: 'remark',
                span: 24
              }
            ]
          }
        },
        plan: {
          priorityList: [], //优先级列表
          loading: false,
          option: {
            height: '33vh',
            calcHeight: 30,
            tip: false,
            searchShow: true,
            searchMenuSpan: 5,
            searchLabelWidth: 100,
            border: true,
            index: false,
            indexLabel: '序号',
            viewBtn: false,
            editBtn: false,
            addBtn: false,
            delBtn: true,
            refreshBtn: false,
            columnBtn: false,
            addRowBtn: false,
            cancelBtn: false,
            selection: false,
            dialogClickModal: false,
            menu: false,
            menuWidth: 80,
            labelWidth: 160,
            dialogDrag: true,
            highlightCurrentRow: true,
            column: fixedColumns
          },
          data: [
            {
              sectionAndLine: ['', ''],
              priority: '',
              sectionPlanQuantity: undefined,
              uph: undefined,
              linePlanQuantity: '',
              sectionRemainingQuantity: ''
            }
          ]
        },
        operateRecord: {
          loading: false,
          option: {
            height: '300px',
            calcHeight: 30,
            tip: false,
            searchShow: true,
            searchMenuSpan: 5,
            searchLabelWidth: 100,
            border: true,
            index: true,
            indexLabel: '序号',
            viewBtn: false,
            editBtn: false,
            addBtn: false,
            delBtn: true,
            refreshBtn: false,
            columnBtn: false,
            addRowBtn: false,
            cancelBtn: false,
            selection: false,
            dialogClickModal: false,
            menu: false,
            menuWidth: 80,
            labelWidth: 160,
            dialogDrag: true,
            highlightCurrentRow: true,
            column: [
              {
                label: '操作时间',
                prop: 'createTime'
              },
              {
                label: '操作人',
                prop: 'createUserName'
              },
              {
                label: '备注',
                prop: 'remark',
                overHidden: true
              }
            ]
          },
          data: []
        }
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    dateColumns() {
      let dates = [];
      this.dispatchDialog.plan.option.column.slice(fixedColumns.length).map((month) => {
        month.children.map((day) => {
          dates.push({
            date: day.prop,
            isWorkday: month.isWorkday
          });
        });
      });
      return dates;
    },
    notDispatchSectionList() {
      return this.sectionStatusList.filter((item) => item.planStatus == 1).map((s) => s.sectionName);
    },
    dispatchIngSectionList() {
      return this.sectionStatusList.filter((item) => item.planStatus == 2).map((s) => s.sectionName);
    },
    dispatchedSectionList() {
      return this.sectionStatusList.filter((item) => item.planStatus == 3).map((s) => s.sectionName);
    },
    computedPriority(priority) {
      return (priority) => {
        let find = this.dispatchDialog.plan.priorityList.find((item) => item.value === priority);
        return find ? find.label : '';
      };
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visible: {
      handler(value) {
        this.dialogVisible = value;
      },
      immediate: true
    }
  },
  mounted() {
    this.dispatchDialog.plan.option.column = fixedColumns;
    getDictionary({ code: 'PRIORITY' }).then((res) => {
      if (res && res.status == 200) {
        this.dispatchDialog.plan.priorityList = res.data.data.map((d) => {
          return {
            label: d.dictValue,
            value: Number(d.dictKey)
          };
        });
      }
    });
  },
  methods: {
    setWorkOrderInfo(data) {
      this.$nextTick(() => {
        this.$set(this.dispatchDialog.workOrderInfo.form, 'workOrderNo', data.workOrderNo);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'type', data.type);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'planQuantity', data.planQuantity);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'status', data.status);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'productPartNo', data.productPartNo);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'productPartModel', data.productPartModel);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'productPartName', data.productPartName);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'productPartNo', data.productPartNo);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'customerCode', data.customerCode);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'customerName', data.customerName);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'planStartTime', data.planStartTime);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'planEndTime', data.planEndTime);
        // this.$set(this.dispatchDialog.workOrderInfo.form, 'remark', data.remark);
        this.$set(this.dispatchDialog.workOrderInfo.form, 'woProcessStatus', data.woProcessStatus);
        this.workOrderId = data.id;
        Promise.all([
          this.handleGetDispatchRemark(data.workOrderNo), // 1.获取排程备注;
          this.handleGetProductLineSection(), // 2.获取工段产线列表;
          this.handleGetLineDispatchList(), // 3.获取产线派工列表信息;
          this.handleGetOperationRecord(data.workOrderNo) // 4.获取操作记录
        ]);
      });
    },
    async handleGetDispatchRemark(workOrderNo) {
      let data = await getOperationLog(workOrderNo);
      if (data.data.code == 200 && data.data.data) {
        this.dispatchDialog.workOrderInfo.form.remark = data.data.data.remark;
      } else {
        this.dispatchDialog.workOrderInfo.form.remark = '';
      }
    },
    async handleGetOperationRecord(workOrderNo) {
      let data = await getOperationList(workOrderNo);
      if (data.data.code == 200 && data.data.data) {
        this.dispatchDialog.operateRecord.data = data.data.data;
      } else {
        this.dispatchDialog.operateRecord.data = [];
      }
    },
    // 获取工段产线列表
    handleGetProductLineSection() {
      getProductLineSection().then((res) => {
        let data = res.data.data;
        this.productLineSection = data.map((d) => {
          let item = {
            label: d.name,
            value: d.id,
            code: d.code,
            productWorkSectionId: d.productWorkSectionId,
            hasChildren: d.lineList && d.lineList.length > 0 ? true : false
          };
          if (d.lineList && d.lineList.length > 0) {
            item.children = d.lineList.map((l) => {
              return {
                label: l.lineName,
                value: l.lineId,
                code: l.lineCode
              };
            });
          }
          return item;
        });
      });
    },
    handleGetLineDispatchList() {
      this.dispatchDialog.plan.loading = true;
      let { queryTimeStart, queryTimeEnd } = this.handleGetQueryTime();
      getPlanInfoList({
        workOrderId: this.workOrderId,
        queryTimeStart,
        queryTimeEnd
      })
        .then((res) => {
          let data = res.data.data;
          this.dateNonWorkingList = data.dateNonWorkingList;
          this.sectionStatusList = data.sectionStatusList;
          if (data.planLineInfoVoList && data.planLineInfoVoList.length > 0) {
            data.planLineInfoVoList.forEach((item) => {
              item.id = item.lineId + new Date().getTime();
              item.sectionAndLine = [item.sectionId, item.lineId];
              if (item.planDateInfoList && item.planDateInfoList.length > 0) {
                item.planDateInfoList.forEach((dateItem) => {
                  dateItem.isWorkday = false;
                  item[dateItem.dayPlanDate + ':dayPlanQuantity'] = dateItem.dayPlanQuantity || 0;
                  item[dateItem.dayPlanDate + ':dayPlanWorkHour'] = dateItem.dayPlanWorkHour || 0;
                  item[dateItem.dayPlanDate + ':dayRemainingWorkHourOfLine'] = dateItem.dayRemainingWorkHourOfLine || 0;
                });
              }
            });
          }
          this.dispatchDialog.plan.data = data.planLineInfoVoList;
          let dateColums = getDay(this.backDay).map((item, index) => {
            let [date, week] = item.split(':');
            return {
              prop: date,
              label: date + '(' + week + ')',
              align: 'center',
              isWorkday: 0,
              children: [
                {
                  label: '剩余工时',
                  prop: date + ':dayRemainingWorkHourOfLine',
                  width: 80,
                  align: 'center'
                },
                {
                  label: '计划数量',
                  prop: date + ':dayPlanQuantity',
                  width: 80,
                  align: 'center'
                },
                {
                  label: '计划工时',
                  prop: date + ':dayPlanWorkHour',
                  width: 80,
                  align: 'center'
                }
              ]
            };
          });
          console.log(dateColums, 'dateColums');
          this.dispatchDialog.plan.option.column = fixedColumns.concat(dateColums);
          this.$refs.dispatchCrud.refreshTable();
        })
        .finally(() => {
          this.dispatchDialog.plan.loading = false;
        });
    },
    handleChangeBackDay(value) {
      this.handleGetLineDispatchList();
    },
    handleGetQueryTime() {
      let queryTimeStart = this.$moment().format('YYYY-MM-DD 00:00:00');
      let queryTimeEnd = this.$moment().add(this.backDay, 'days').format('YYYY-MM-DD 23:59:59');
      if (this.backDay == 'sameMonth') {
        queryTimeStart = this.$moment().startOf('month').format('YYYY-MM-DD 00:00:00');
        queryTimeEnd = this.$moment().endOf('month').format('YYYY-MM-DD 23:59:59');
      } else if (this.backDay == 'nextMonth') {
        queryTimeStart = this.$moment().startOf('month').subtract('month', -1).format('YYYY-MM-DD 00:00:00');
        queryTimeEnd = this.$moment().endOf('month').subtract('month', -1).format('YYYY-MM-DD 23:59:59');
      }
      return { queryTimeStart, queryTimeEnd };
    },
    closeDialog() {
      const that = this;
      that.backDay = 0;
      that.dispatchDialog.plan.data = [];
      that.dialogVisible = false;
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .workorderPlanDetailDialog {
  .el-dialog__body {
    padding: 0px 20px 5px;
  }
  .avue-crud__menu {
    min-height: auto;
    margin-bottom: 15px;
  }
  .el-table__fixed-header-wrapper {
    .el-icon-plus {
      cursor: pointer;
      font-weight: bold;
      color: rgb(102, 177, 255);
    }
  }
  .lineDispatchTable {
    .el-table .cell {
      padding-left: 2px;
      padding-right: 2px;
      .el-input-number {
        width: 100%;
      }
    }
  }
  .dispatch-title {
    display: flex;
    align-items: center;
    margin: 15px 0;
    &-dot {
      background-color: rgb(102, 177, 255);
      width: 10px;
      height: 20px;
      margin-right: 8px;
    }
    &-text {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .dispatch-menu {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .leftWorkSection {
      display: flex;
      align-items: center;
      span {
        display: inline-block;
        height: 14px;
        width: 14px;
        margin: 0 3px;
        &.finished {
          background-color: #95f204;
          &:before {
            content: '\2713';
            display: inline-block;
            width: 14px;
            height: 14px;
            color: #fff;
            font-size: 12px;
            vertical-align: super;
          }
        }
        &.finishing {
          background-color: #03a7f0;
        }
        &.notFinish {
          background-color: #ccc;
        }
      }
    }
    .rightInfo {
      display: flex;
      align-items: center;
      .legendList {
        display: flex;
        margin-right: 10px;
        .legendItem {
          margin-right: 3px;
          display: flex;
          align-items: center;
          span {
            display: inline-block;
            height: 14px;
            width: 14px;
            margin-right: 3px;
            &.finished {
              background-color: #95f204;
              &:before {
                content: '\2713';
                display: inline-block;
                width: 14px;
                height: 14px;
                color: #fff;
                font-size: 12px;
                vertical-align: super;
              }
            }
            &.finishing {
              background-color: #03a7f0;
            }
            &.notFinish {
              background-color: #ccc;
            }
          }
        }
      }
      .dateDisplay {
        display: flex;
        align-items: center;
      }
    }
  }
  .workInfoForm {
    .avue-form__group {
      .el-form-item {
        // margin-bottom: 5px;
      }
      .avue-form__menu {
        display: none;
      }
    }
  }
  .el-dialog__footer {
    padding: 10px 20px 10px;
  }
}
</style>
